// https://taro-ext.jd.com/plugin/view/5d394d3a9b6a1d4027780173
import React, { useEffect, useState } from "react";
import Taro, {
  useReachBottom,
  usePullDownRefresh,
  useRouter,
  useDidShow,
} from "@tarojs/taro";
import GoodsItem from "@/components/GoodsItem";
import onPay from "@/common/utils/pay";
import createContract from "@/common/utils/createContract";
import { View, Image, Text } from "@tarojs/components";

import ListStatusInfo from "@/components/ListStatusInfo";

import * as api from "./api";
import "./index.scss";

const Index: React.FC<{}> = () => {
  const [data, setData] = useState<any>({});
  const [loading, setLoading] = useState(false);
  const [isOpen, setIsOpen] = useState(false);
  const [count, setCount] = useState(0);
  const [activeKey, setActiveKey] = useState("message");
  const [padding, setPadding] = useState(0);
  const router = useRouter();
  const [flag, setFlag] = useState(false);
  const [tabMap, setTabMap] = useState<any>({
    message: {
      text: "消息",
      total: null,
      current: null,
      data: [],
      isShow: true,
      isLoaded: false,
    },
    notice: {
      text: "公告",
      total: null,
      current: null,
      data: [],
      isShow: true,
      isLoaded: false,
    },
  });

  const getList = async (current_page = 1) => {
    try {
      setLoading(true);
      Taro.showNavigationBarLoading();
      const { result, status } = await api[`${activeKey}_search`]({
        current_page: current_page,
      });
      if (status === "ok") {
        const newTabMap = { ...tabMap };
        newTabMap[activeKey].current = current_page;
        newTabMap[activeKey].isLoaded = true;
        newTabMap[activeKey].data =
          current_page === 1
            ? [].concat(result.data_list)
            : newTabMap[activeKey].data.concat(result.data_list);
        newTabMap[activeKey].total = result.total;
        setTabMap(newTabMap);
      }
    } catch (err) {
      console.log("err--------->>>", err);
    } finally {
      Taro.hideNavigationBarLoading();
      Taro.stopPullDownRefresh();
      setLoading(false);
    }
  };

  const getUnReadCount = async () => {
    try {
      setLoading(true);
      Taro.showNavigationBarLoading();
      const { result, status } = await api.message_unreadcount({});
      if (status === "ok") {
        setCount(result.unread_count);
      }
    } catch (err) {
      console.log("err--------->>>", err);
    } finally {
      Taro.hideNavigationBarLoading();
      setLoading(false);
    }
  };

  const changeStatus = async (message_id) => {
    try {
      setLoading(true);
      Taro.showNavigationBarLoading();
      const { result, status } = await api.message_changestatus({ message_id });
      if (status === "ok") {
        // setCount(result.unread_count);
      }
    } catch (err) {
      console.log("err--------->>>", err);
    } finally {
      Taro.hideNavigationBarLoading();
      setLoading(false);
    }
  };

  useReachBottom(() => {
    if (tabMap[activeKey].data.length < tabMap[activeKey].total) {
      getList(tabMap[activeKey].current + 1);
    }
  });

  usePullDownRefresh(() => {
    getList(1);
  });

  useDidShow(() => {
    setFlag(!flag);
    getUnReadCount();
    if (!tabMap[activeKey].isLoaded) {
      getList(1);
    }
  });

  useEffect(() => {
    console.log(Taro.getMenuButtonBoundingClientRect());
    const menuInfo = Taro.getMenuButtonBoundingClientRect();
    setPadding(menuInfo.top * 2 + menuInfo.height);
    if (!tabMap[activeKey].isLoaded) {
      getList(1);
    }
  }, [activeKey]);

  const goDetail = (noticeItem: any) => {
    console.log("notice-item----->>", noticeItem);
    if (noticeItem.id) {
      changeStatus(noticeItem.id);
    }
    Taro.navigateTo({
      url: "/pages/noticeDetail/index?data=" + JSON.stringify(noticeItem),
    });
  };

  return (
    <View className="notice-list-page">
      <View className="tabs">
        {Object.entries(tabMap).map((item) => {
          if (item[1].isShow) {
            return (
              <View
                key={item[0]}
                className={activeKey === item[0] ? "tab tab__active" : "tab"}
                onClick={() => {
                  setActiveKey(item[0]);
                }}
                // style={`height:${padding}px`}
              >
                <View>{item[1].text}</View>
                {item[0] === "message" && count ? (
                  <View className="status">{count}</View>
                ) : null}
                <View className="line"></View>
              </View>
            );
          }
        })}
      </View>

      {/* {JSON.stringify(item.order_item_list)} */}

      {tabMap[activeKey].data.map((item) => {
        return (
          <View
            key={item.content}
            className="item"
            onClick={() => goDetail(item)}
          >
            <View className="title">
              <View className="text">{item.title}</View>
              {activeKey === "message" && item.status === "unread" ? (
                <View className="status"></View>
              ) : null}
            </View>
            <View className="content">{item.content}</View>
            <View className="time">{item.create_time}</View>
          </View>
        );
      })}

      <ListStatusInfo
        total={tabMap[activeKey].total}
        dataLength={tabMap[activeKey].data.length}
        loading={loading}
      />
    </View>
  );
};

export default Index;
